/*
 * Copyright 2014 by État de Genève (Switzerland)
 * All rights reserved.
 *
 * Author: ELCA Informatique SA
 */
define([
        'requisitions/transmettreEdit',
        'services/dataservice',
        'services/notifier',
        'durandal/app',
        'plugins/dialog'
    ],
    function (TransmettreDetail, ds, notifier, app, dialog) {

        var transmitAction = function () {
            this.icon = 'mi mi-files-11';
            this.name = 'Transmettre';
        };

        /**
         * doAction will have for this context the listTemplate module
         */
        transmitAction.prototype.doAction = function () {
            dialog.showBS3Dialog(new TransmettreDetail()).then(function (transmettreToUser) {

                if (this.checks() && this.checks().length > 0 && transmettreToUser) {
                    var messageIdArray = [];

                    _.each(this.checks(), function (index) {
                        var item = this.items()[index];
                        if(item) {
                            messageIdArray.push(item[this.primaryColumnIndex()]);
                        }
                    }.bind(this));

                    var transmettreDto = { messageIds: messageIdArray, userId: transmettreToUser };
                    ds.multiTransmettre(transmettreDto)
                        .then(triggerRefresh.bind(this));

                }
            }.bind(this));
        };

        function triggerRefresh() {
            this.globalCheck(false);
            this.checks([]);
            app.trigger('cms:menu:forceRefresh');
        }

        return transmitAction;

    });